package com.Dao.Imp;

import com.Dao.GetBookDao;
import com.Utils.C3P0Utils;
import com.pojo.Book;
import com.pojo.BookExamine;
import com.pojo.BookProfile;
import com.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class GetBookInfoDaoImp implements GetBookDao {
    @Override
    public Map<String,Object> getBookInfo(int page,int rows) throws SQLException {
        Map<String,Object> map=new HashMap<>();
        if(page==0){
            page=1;
        }
        QueryRunner queryRunner=new QueryRunner(C3P0Utils.getDataSource());
        //获取总数
        String sqlCount=" select count(1) from books_detail ";
        Long totalCount = queryRunner.query(sqlCount, new ScalarHandler<Long>());
        int start = (page - 1) * rows; // 起始行索引
        String query = "SELECT id,bookName,author,mainsignature,bookImage,status FROM books_detail LIMIT " + start + ", " + rows;
        List<Book> list=queryRunner.query(query,new BeanListHandler<>(Book.class));
        // 计算总页数
        int totalPages = (int) Math.ceil((double) totalCount / rows);
        map.put("list",list);
        map.put("totalPages",totalPages);
        return map;
    }

    @Override
    public List<BookProfile> getBookProfile(int bookId) throws SQLException {
        QueryRunner queryRunner=new QueryRunner(C3P0Utils.getDataSource());
        String sql="select profile,snopsis from books_detail where id=?";
        List<BookProfile> bookProfiles=queryRunner.query(sql,new BeanListHandler<>(BookProfile.class),bookId);
        return bookProfiles;
    }

    @Override
    public Map<String,Object> getApplyBook(int page,int rows) throws SQLException {
        Map<String,Object> map=new HashMap<>();
        if(page==0){
            page=1;
        }
        QueryRunner queryRunner=new QueryRunner(C3P0Utils.getDataSource());
        //获取总数
        String sqlCount=" select count(1) from bookTemportary ";
        Long totalCount = queryRunner.query(sqlCount, new ScalarHandler<Long>());
        int start = (page - 1) * rows; // 起始行索引
        String query = "SELECT id,author,bookName,mainsignature,bookImage,profile,file FROM bookTemportary LIMIT " + start + ", " + rows;
        List<BookExamine> list=queryRunner.query(query,new BeanListHandler<>(BookExamine.class));
        // 计算总页数
        int totalPages = (int) Math.ceil((double) totalCount / rows);
        map.put("list",list);
        map.put("totalPages",totalPages);
        return map;
    }
}
